package org.csu.gp_store.common;

import lombok.Data;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EmailCodeList {
    static {
        emailCodeList = new ArrayList<>();
    }

    // 对外开放的四个常量
    public static int BUYER_ACCOUNT_REGISTER = 1;
    public static int BUYER_ACCOUNT_CANCEL = 2;
    public static int COMPANY_ACCOUNT_REGISTER = 3;
    public static int COMPANY_ACCOUNT_CANCEL = 4;

    private static final List<EmailCode> emailCodeList;

    private static void insertCode(EmailCode emailCode) {
        emailCodeList.add(emailCode);
    }

    /**
     * 对外开放的方法
     *
     * @param email  邮箱
     * @param method 方法
     * @return 验证码
     * @author huangzhangyan
     * @date 2022/7/7 14:22
     */
    public static String getCode(String email, int method) {
        for (EmailCode emailCode : emailCodeList) {
            // 超时删去 释放内存
            if (emailCode.getEndTime().getTime() < new Date().getTime()) {
                emailCodeList.remove(emailCode);
                continue;
            }
            // 匹配到
            if (emailCode.getEmail().equals(email) && emailCode.getMethod() == method) {
                System.out.println("email: " + email + "method: " + method + "找到匹配的code: " + emailCode.getVerifyCode());
                return emailCode.getVerifyCode();
            }
        }
        System.out.println("email: " + email + "method: " + method + " 未找到对应的code");
        return null;
    }

    /**
     * 对外开放的方法
     * 发送邮箱时,添加EmailCode进入EmailCodeList管理
     *
     * @author huangzhangyan
     * @date 2022/7/7 14:22
     */
    public static void addCode(String email, String verifyCode, int method) {
        insertCode(new EmailCode(email, verifyCode, method));
    }

    @Data
    private static class EmailCode {
        private String email;  //验证码对应的账号
        private String verifyCode; //生成的验证码
        private Date endTime; //有效时间限制
        private int method;

        private EmailCode(String email, String verifyCode, int method) {
            this(email, verifyCode, new Date(new Date().getTime() + 300000), method);
        }

        private EmailCode(String email, String verifyCode, Date endTime, int method) {
            this.email = email;
            this.verifyCode = verifyCode;
            this.endTime = endTime;
            this.method = method;
        }
    }
}
